<template>
  <div>
    <div
      class="w-[350px] border border-gray-200 bg-white p-3 shadow-md rounded-lg"
      @click="openDrawer"
    >
      <Handle type="target" :position="Position.Left" />
      <div class="flex flex-col gap-y-1">
        <common-title-module />
        <CommonDisplayModule title="输入" value-name="vartype" :valueList="data?.inoutlist" />
        <CommonDisplayModule title="输出" value-name="vartype" :valueList="data?.commonoutvo" />
      </div>
      <Handle type="source" :position="Position.Right" />
    </div>
    <WriteDrawerModule
      ref="drawerRef"
      :title="node?.node?.label"
      desc="写入节点可以添加 文本类型 的知识库，仅可以添加一个知识库"
      :form="data"
      @add="handleClickAddBtn"
      @remove="handleClickDeleteBtn"
      @cancel="onCancel"
    />
  </div>
</template>
<script setup>
import { ref } from 'vue'
import { Handle, Position, useNode, useVueFlow } from '@vue-flow/core'
import { DOCSTRATEGY_OPTIONS, SEGMENTATION_OPTONS, SYMBOL_TYPE_OPTIONS } from '../../lib/constant'
import { editNode } from '@/api/modules/flow'
import CommonTitleModule from '../modules/common-title-module.vue'
import CommonDisplayModule from '../modules/common-display-module.vue'
import WriteDrawerModule from '../modules/write-drawer-module.vue'

const node = useNode()
const data = ref({
  knowledgeid: node.node.data.knowledgeid || '',
  docstrategy: node.node.data.docstrategy || DOCSTRATEGY_OPTIONS[0].value,
  segmentstrategy: node.node.data.segmentstrategy || SEGMENTATION_OPTONS[0].value,
  segmenttag: node.node.data.segmenttag || SYMBOL_TYPE_OPTIONS[0].value,
  precise: node.node.data.precise ? node.node.data.precise.split(',') : [],
  segmentmaxilength: node.node.data.segmentmaxilength || 1000,
  minmatch: node.node.data.minmatch || .1,
  content: node.node.data.content || '',
  inoutlist: node.node.data.inoutlist || [
    {
      varname: 'knowledge',
      varparam: '',
      vartype: 'File/Doc'
    }
  ],
  commonoutvo: [
    {
      varname: 'documentId',
      vartype: 'String'
    },
    {
      varname: 'fileName',
      vartype: 'String'
    },
    {
      varname: 'fileUrl',
      vartype: 'String'
    }
  ]
})


const drawerRef = ref(null)
const openDrawer = () => {
  drawerRef.value?.init()
}

function handleClickAddBtn(listKey) {
  data.value[listKey].push({
    name: '',
    value: '',
    type: 'String'
  })
  node.node.data = {
    ...node.node.data,
    output: data
  }
}

function handleClickDeleteBtn(listKey, index) {
  data.value[listKey].splice(index, 1)
  node.node.data = {
    ...node.node.data,
    output: data
  }
}

const onCancel = () => {
  const knowledgename = drawerRef.value.knowledgeList.map(item=>item.name)
  editNode({
    data: {
      id: node.id,
      ...data.value,
      precise: data.value.precise.toString(),
      commonoutvo: data.value.commonoutvo.reduce((pre, cur) => {
        pre[cur.varname] = cur.vartype
        return pre
      }, {})
    }
  })
}
</script>
